<template>
  <!-- // 地图 -->
  <div class="homePageCards1">
    <div class="full-box" @click="fullscreen">
      <img src="../../../../assets/img/full.png" alt="" />
      <span>{{this.isFullscreen?'返回':'全屏'}}</span>
    </div>
    <div id="warrmap" style="width: 100%; height: 100%"></div>
    <div id='layercards'></div>
    <el-dialog title="站内图查看" :visible.sync="showDzZnt" width="50%">
      <div id="zntcontainer" style="width:100%;height:600px" v-if="showDzZnt">zntcontainer</div>
    </el-dialog>
  </div>
</template>
<script>
import sjccKey from "../../../../config/sjmapkey";
export default {
  name: "MapContent",
  components: {},
  props: {
    layerCard: {
      type: Boolean,
      default: true
    },
    cityName: {
      type: String,
      default: ""
    },
    mapCenter: {
      type: Array,
      default: () => [112.96730140947924, 30.574022147218216]
    },
    mapZoom: {
      type: Number,
      default: 8
    }
  },
  data: function () {
    return {
      map: null, // 基础地图
      showDzZnt: false,
      PSRMap: null, // 电网资源地图
      movePointMarker: null,
      lineCheckAll: true,
      isZkSelect: false,
      dzCheckAll: true,
      FullScreen: false,
      isFullscreen: false,
      classid: [296, 110, 200, 300, 335, 342, 521, 1300],
      voltage: [1000000, 500000, -800000, 220000, 110000, 35000],
      classidList: [
        {
          name: "发电站",
          devType: "xnfjd",
          value: 296
        },
        {
          name: "变电站",
          devType: "zf01",
          value: 110
        },
        {
          name: "输电线路",
          devType: "xl",
          value: 200
        },
        {
          name: "直流线路",
          devType: "zlxl",
          value: 1300
        },
        {
          name: "馈线",
          devType: "dkx",
          value: 300
        },
        {
          name: "配电台变",
          devType: "0110",
          value: 335
        },
        {
          name: "柱上开关",
          devType: "0113",
          value: 342
        },
        {
          name: "低压落火点",
          devType: "3112",
          value: 521
        }
      ],
      voltageList: [
        {
          name: "1000kV",
          value: 1000000
        },
        {
          name: "800kV",
          value: -800000
        },
        {
          name: "500kV",
          value: 500000
        },
        {
          name: "220kV",
          value: 220000
        },
        {
          name: "110kV",
          value: 110000
        },
        {
          name: "35kV",
          value: 35000
        }
      ]
    };
  },
  beforeDestroy() {
    this.map && this.map.remove();
    this.map = null;
    this.$eventBus.$off("createlayer");
  },
  mounted() {
    this.initGisMaps();
    window.handleSee = this.handleSee;
    window.handleSeeVideo = this.handleSeeVideo;
    window.addEventListener("resize", this.onresize);
  },
  computed: {
    typeNames() {
      return this.classidList.filter((i) => i.value === true);
    }
  },
  watch: {
    // 100000线路，300000电站
    classid: {
      handler(val) {
        this.queryRender({
          classid: val,
          voltage: this.voltage,
          visiable: true,
          mode: "all"
        });
      },
      deep: true
    },
    voltage: {
      handler(val) {
        this.queryRender({
          classid: this.classid,
          voltage: val,
          visiable: true,
          mode: "all"
        });
      },
      deep: true
    }
  },
  methods: {
    // 根据环境显示不同的地图组件
    initGisMaps() {
      if (process.env.NODE_ENV === "production") {
        this.initPlugin();
      } else {
        this.initLocalMap();
      }
    },
    // 加载插件
    /* global NARIMap */
    /* global Require */
    initPlugin() {
      Require(["PSRMap", "Tools", "SpatialAnalyst"], () => {
        if (NARIMap.Config.examples.notlogin) {
          this.initMap(NARIMap.Config.styles.base);
        } else {
          // 电网GIS地图服务登录
          NARIMap.SGAuth.login()
            .then((result) => {
              if (result.success) {
                console.log("登录成功");
              } else {
                console.log("登录失败", result);
              }
              // 默认打开电网GIS基础地图
              this.initMap(NARIMap.Config.styles.sjBase);
            })
            .catch((err) => {
              console.log("错误", err);
            });
        }
      });
    },
    // 初始化地图
    initMap(styleurl) {
      this.map = new NARIMap.Map({
        // 地图绑定的DOM元素ID
        container: "warrmap",
        // 地图样式
        style: styleurl,
        // 默认缩放层级
        zoom: this.mapZoom,
        // 地图中心点
        center: this.mapCenter,
        // 地图默认字体
        localIdeographFontFamily: "Microsoft YoHei"
        // controls:['navigation']
      });

      this.map.on("load", () => {
        this.initLayer();
        // window.map = this.map;
        // 添加电网图层
        if (this.layerCard) {
          this.initLayerCard();
        }
        // SGMap.plugin(["SGMap.DistrictTask"]).then(()=>{
        //        this.search('武汉市');
        // });
        if (this.cityName) {
          SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
            this.search(this.cityName);
          });
        }
        this.$eventBus.$on("createlayer", (name) => {
          console.log("定位城市", name);
          SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
            this.search(name);
          });
        });
      });
    },
    handleCheckedDzChange(val) {
      this.dzCheckAll = this.classidList.length === val.length;
    },
    handleCheckedLineChange(val) {
      this.lineCheckAll = this.voltageList.length === val.length;
    },
    showXlt() {
      this.isZkSelect = !this.isZkSelect;
    },
    /* global LayerCards */
    initLayerCard() {
      SGMap.plugin(["SGMap.RoadNetLayer"]).then(() => {
        window.l = new LayerCards({
          map: this.map.pmap,
          container: "layercards"
        });
      });
    },
    drawHouse(center) {
      center = center.split(",");
      const arr = [];
      for (let i = 0; i < 4; i++) {
        const rad1 = (Math.random() - 0.5) * 0.5;
        const rad2 = (Math.random() - 0.5) * 0.5;
        // let cent1 = [center[0] * 1 + rad1, center[1] * 1 + rad2];
        arr.push({longitude: center[0] * 1 + rad1, latitude: center[1] * 1 + rad2, id: i});
      }
      arr.forEach((item) => {
        this.popupInfoWindow = new SGMap.Popup({
          closeButton: false,
          closeOnClick: false,
          anchor: "top-left",
          offset: [10, 10]
        });
        var url = require("../../../../assets/img/fangzi.png");
        this.map.loadImage(url, (error, image) => {
          this.map.addImage("houseImg" + item.id, image);
          this.map.addLayer({
            id: "houseLayer" + item.id,
            type: "symbol",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: "Point",
                      coordinates: [item.longitude, item.latitude]
                    },
                    properties: {
                      name: ""
                    }
                  }
                ]
              }
            },
            layout: {
              "icon-image": "houseImg" + item.id,
              "icon-size": 0.20,
              "icon-ignore-placement": true,
              "text-ignore-placement": false,
              "text-size": 12,
              "text-anchor": "top",
              "text-allow-overlap": false,
              "icon-anchor": "center",
              "text-offset": [0, 0],
              "text-max-width": 8,
              "text-font": ["Microsoft YaHei Regular"]
            },
            paint: {
              "text-color": "#555252",
              "text-halo-color": "#FFFFFF",
              "text-halo-width": 1.33333
            }
          });
        });
      });
    },
    drawLine(center, j) {
      center = center.split(",");
      const arr = [];
      for (let i = 0; i < 2; i++) {
        const rad1 = (Math.random() - 0.5) * 0.5;
        const rad2 = (Math.random() - 0.5) * 0.5;
        // const cent1 = [center[0] * 1 + rad1, center[1] * 1 + rad2];
        arr.push({ longitude: center[0] * 1 + rad1, latitude: center[1] * 1 + rad2, id: "" + j + i, stationName: "", isStation: true });
      }
      const lindata = [];
      arr.forEach((item) => {
        if (item.isStation) {
          var url = require("../../../../assets/img/dwtb.png");
          this.map.loadImage(url, (error, image) => {
            this.map.addImage("stationImg" + item.id, image);
            this.map.addLayer({
              id: "station" + item.id,
              type: "symbol",
              source: {
                type: "geojson",
                data: {
                  type: "FeatureCollection",
                  features: [
                    {
                      type: "Feature",
                      geometry: {
                        type: "Point",
                        coordinates: [item.longitude, item.latitude]
                      },
                      properties: {
                        name: item.stationName
                      }
                    }
                  ]
                }
              },
              layout: {
                "icon-image": "stationImg" + item.id,
                "icon-size": 0.04,
                "icon-ignore-placement": true,
                "text-ignore-placement": false,
                "text-size": 16,
                "text-anchor": "top",
                "text-allow-overlap": false,
                "icon-anchor": "bottom",
                "text-offset": [0, 0],
                "text-field": item.stationName,
                "text-max-width": 8,
                "text-font": ["Microsoft YaHei Regular"]
              },
              paint: {
                "text-color": "#555252",
                "text-halo-color": "#FFFFFF",
                "text-halo-width": 1.33333
              }
            });
          });
        }
        lindata.push([item.longitude, item.latitude]);
      });
      this.drawPolyLine(lindata, j);
    },
    // 画折线
    drawPolyLine(lindata, j) {
      this.map.addLayer({
        id: "power-line" + j,
        type: "line",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: [
              {
                type: "Feature",
                geometry: {
                  type: "LineString",
                  coordinates: lindata
                }
              }
            ]
          }
        },
        layout: {
          "line-cap": "round",
          "line-join": "round"
        },
        paint: {
          "line-color": "#dc6f43",
          "line-width": 4,
          "line-opacity": 0.8,
          "line-offset": 5,
          "line-dasharray": [2, 2]
        }
      });
    },
    fullscreen() {
      // 进入全屏
      var docElm = document.querySelector(".homePageCards1"); // 指定容器id
      if (!this.FullScreen) {
        // 兼容W3C
        if (docElm.requestFullscreen) {
          docElm.requestFullscreen();
        } else if (docElm.mozRequestFullScreen) {
          // 兼容FireFox
          docElm.mozRequestFullScreen();
        } else if (docElm.webkitRequestFullScreen) {
          // 兼容Chrome等
          docElm.webkitRequestFullScreen();
        } else if (docElm.msRequestFullscreen) {
          docElm.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
      this.FullScreen = !this.FullScreen;
    },
    // 根据筛选条件过滤
    queryRender(options) {
      this.psrmap && this.psrmap.filter(options);
    },
    clearHouse() {
      for (let i = 0; i < 4; i++) {
        this.map.getLayer(`houseLayer${i}`) && this.map.removeLayer(`houseLayer${i}`);
        this.map.getSource(`houseLayer${i}`) && this.map.removeSource(`houseLayer${i}`);
        this.map.hasImage(`houseImg${i}`) && this.map.removeImage(`houseImg${i}`);
      }
    },
    clearManAndLine() {
      for (let i = 0; i < 2; i++) {
        this.map.hasImage(`stationImg${i}0`) && this.map.removeImage(`stationImg${i}0`);
        this.map.hasImage(`stationImg${i}1`) && this.map.removeImage(`stationImg${i}1`);
        this.map.getLayer(`station${i}0`) && this.map.removeLayer(`station${i}0`);
        this.map.getLayer(`station${i}1`) && this.map.removeLayer(`station${i}1`);
        this.map.getLayer(`power-line${i}`) && this.map.removeLayer(`power-line${i}`);
        this.map.getSource(`station${i}0`) && this.map.removeSource(`station${i}0`);
        this.map.getSource(`station${i}1`) && this.map.removeSource(`station${i}1`);
        this.map.getSource(`power-line${i}`) && this.map.removeSource(`power-line${i}`);
      }
    },
    // 全选
    stationChange(val) {
      this.classid = val ? this.classidList.map(i => i.value) : [];
    },
    lineChange(val) {
      this.voltage = val ? this.voltageList.map(i => i.value) : [];
    },
    initLayer() {
      this.map.addLayer({
        id: "province-polygon",
        type: "fill",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        paint: {
          "fill-color": "#206bf5",
          "fill-opacity": 0.3
        }
      });
      this.map.addLayer({
        id: "province-line",
        type: "line",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        layout: {
          "line-cap": "round",
          "line-join": "round"
        },
        paint: {
          "line-color": "#3995ea",
          "line-width": 2
        }
      });
    },
    // 创建站内图
    initZnMap(details) {
      console.log(details);
      const stationmap = new NARIMap.StationMap();
      // 总部、省侧psrType不同，需要动态获取
      // const devType = NARIMap.PsrTypeMapper.classIdToPsrTypes([110])[0];
      stationmap.init({
        // 地图绑定的DOM元素ID
        container: "zntcontainer",
        station: {
          devid: details.psrId, // 设备id
          classid: 110, // 图层类型
          vlogate: Number(details.vlevelCode), // 电压等级
          deviceType: details.psrType, // 国网设备类型
          distribution: 1, // 主配网标志
          provinceId: details.provinceId// 分省ID
        },
        fullExtent: NARIMap.Config.examples.fullExtent,
        isLoadAnno: false,
        onload: () => {
          // 添加设备点击事件
          // stationmap.getPsrMap().on("click", (features) => {
          //   console.log(features);
          // });
        }
      });
    },
    search(name) {
      this.clearHouse();
      this.clearManAndLine();
      const districtTask = new SGMap.DistrictTask();
      districtTask
        .searchDistrict({
          keyword: name,
          extension: true,
          subdistrict: "1"
        })
        .then((result) => {
          if (!result.data) return;
          result = result.data;
          if (!result.districts) {
            return;
          }
          var provinceFeatures = [];
          for (var i = 0; i < result.districts.length; i++) {
            provinceFeatures.push({
              type: "Feature",
              geometry: result.districts[i].shape
            });
          }
          console.log("name", provinceFeatures, result);
          // 更新图层数据
          this.map.getSource("province-polygon").setData({
            type: "FeatureCollection",
            features: provinceFeatures
          });
          this.map.getSource("province-line").setData({
            type: "FeatureCollection",
            features: provinceFeatures
          });
          this.map.flyTo({
            center: result.districts[0].center.split(","),
            zoom: 8
          });
          const center = result.districts[0].center;
          // this.drawHouse(center);
          for (let i = 0; i < 2; i++) {
            this.drawLine(center, i);
          }
        });
    },
    initLocalMap() {
      SGMap.tokenTask.login(sjccKey.appkey, sjccKey.appsecret).then((res) => {
        this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
          container: "warrmap",
          // 地图样式
          style: "aegis://styles/aegis/Streets",
          // 默认缩放层级
          zoom: 8,
          // 地图中心点
          center: [114.36730140947924, 30.574022147218216],
          // 地图默认字体
          localIdeographFontFamily: "Microsoft YoHei"
        });
      });
    },
    onresize(event) {
      // 利用屏幕分辨率和window对象的内高度来判断兼容IE
      const winFlag = window.innerHeight === window.screen.height;
      // 利用window全屏标识来判断 -- IE无效
      const isFull = window.fullScreen || document.webkitIsFullScreen;
      if (isFull === undefined) {
        this.isFullscreen = winFlag;
      } else {
        this.isFullscreen = winFlag || isFull;
      }
      this.FullScreen = this.isFullscreen;
    }
  }
};
</script>

<style scoped lang="less">
:deep(.popupBg) {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  background-image: url("../../../../assets/img/ckDetail.png");
  background-repeat: no-repeat;
}
.homePageCards1 {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 6px;
  border-radius: 5px;
  #map {
    border-radius: 5px;
  }
  :deep(.el-dialog__body) {
    padding: 0;
  }
  :deep(.el-dialog__header) {
    background: #5077ff;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn {
      top: 5px;
      font-size: 30px !important;
    }
    .el-icon-close {
      color: #fff;
    }
    padding: 10px;
  }
}
.grollDiv {
  position: absolute;
  padding: 6px;
  overflow: hidden;
  transition: all 0.5s;
  height: 242px;
  top: 10px;
  left: 10px;
  z-index: 9;
  color: #fff;
  font-size: 12px;
  line-height: 25px;
  .flex-box{
    width: 380px;
    padding: 10px;
    background-color: rgba(255, 255, 255, 0.8);
  }
  .dzTitle {
    font-size: 16px !important;
  }
  .flex-warp {
    flex-wrap: wrap;
  }
  .classid {
    width: 50%;
    margin-top: 8px;
    box-sizing: border-box;
    // text-align: center;
    input {
      width: 40%;
      height: 70%;
    }
    span {
      color: #000;
    }
  }
}
.full-box {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  z-index: 9;
  background-color: #fff;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 5px;

  img {
    width: 15px;
    height: 15px;
    margin-right: 5px;
  }
}
:deep(.epgis-popup) {
  max-width: 600px !important;
}
</style>
